<?php


namespace app\job;


use app\shop\model\user\MessageModel;
use app\shop\model\user\UserModel;
use app\shop\service\chat\ChatService;
use think\facade\Log;
use think\queue\Job;

class OrderJob
{
    /**
     * @Title: fire
     * @Description:
     * @param Job $job
     * @param array $data
     * @throws
     * @author Jack
     */
    public function fire(Job $job, array $data)
    {
        //有些消息在到达消费者时,可能已经不再需要执行了
        $isJobStillNeedToBeDone = $this->checkDatabaseToSeeIfJobNeedToBeDone($data);
        if (!$isJobStillNeedToBeDone) {
            $job->delete();
            return;
        }
        $jobId = $job->getJobId();
        $isJobDone = $this->orders($data, $jobId);
        if ($isJobDone) {
            //如果任务执行成功，记得删除任务
            $job->delete();
        } else {
            //通过这个方法可以检查这个任务已经重试了几次了
            if ($job->attempts() > 3) {
                Log::error('试了3次了');
                $job->delete();

                //也可以重新发布这个任务
                //print("<info>Hello Job will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }

    /**
     * @Title: checkDatabaseToSeeIfJobNeedToBeDone
     * @Description:
     * @param array $data
     * @return boolean
     * @throws
     * @author Jack
     */
    private function checkDatabaseToSeeIfJobNeedToBeDone($data)
    {
        return true;
    }

    /**
     * @Title: orders
     * @Description:
     * @param array $data
     * @throws
     * @author Jack
     */
    public function orders(array $data, $jobId)
    {
        //对订单进行数据库操作或其他等等
//        Log::error(date('Y-m-d H:i:s') . ' 队列收到消息：' . json_encode($data));

        $fromUserId = $data['from_user'];
        $toContactId = $data['to_user'];
        $orderId = $data['order_id'];
        $toUserInfo = UserModel::field('user_id,mobile,realname,avatar,role_id,auto_reply,login_status')
            ->where('user_id', $toContactId)
            ->find();
        if ($toUserInfo['login_status'] == 2) {
            $autoReply = $toUserInfo['auto_reply'] ?: '您好，我现在有事不在，稍后再和您联系。';
            $data = ChatService::getMessageData($toContactId, $fromUserId, $autoReply, 'text', '', 0,
                0, 0, $orderId);
            $message = new MessageModel();
            $message->save($data);
            $sendData = ChatService::getSendData($toContactId, $fromUserId, $autoReply, 'text', 0, $orderId);
            $sendData['auto_reply'] = 1;
            $sendData['msg_id'] = $message->id;
            $sendData['quote'] = new \stdClass();
            wsSendMsg([$fromUserId, $toContactId], 'simple', $sendData, 0);

//            $sendData = ChatService::getSendData($fromUserId, $toContactId, $toUserInfo['auto_reply']);
//            wsSendMsg($toContactId, 'simple', $sendData, 0);
        }
        return true;
    }
}